package com.feicheng.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.base.common.DaoConstant;
import com.feicheng.base.exception.SystemException;
import com.feicheng.base.result.Result;
import com.feicheng.entity.Product;
import com.feicheng.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 新增采购订单商品类型下拉框
 * @param
 * @autor yue.yang
 * @return
 */

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    IProductService iProductService;
    @PostMapping("/type_list/g")
    public Result selectProductType() {
        //构造商品条件查询构造器
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();

        //将商品类型分组查询所有(类别去重)
        productQueryWrapper.groupBy(DaoConstant.PRODUCT.TYPE);
        //productQueryWrapper.select(DaoConstant.PRODUCT.TYPE);

        //只查出商品状态是在售
        productQueryWrapper.eq(DaoConstant.PRODUCT.STATE,
                DaoConstant.VALUE.Y);
        
        //符合条件所有集合
        List<Product> products = iProductService.list(productQueryWrapper);

        //新建一个空的ArrayList
        ArrayList<String> productTypes = new ArrayList<>();

        //循环插入商品类型
        for (Product product: products) {
            productTypes.add(product.getType());
        }
        //返回查询结果
        return Result.success(productTypes);
    }

    /**
     * 采购产品名称下拉框接口
     * @param type 业务参数
     * @author shanshan.zhang
     * @return
     */

    @PostMapping("/product/list/g")
    public Result selectProduct(@RequestParam String type) {

        /* 当type是null的时候、，就抛异常 */
        if(null == type){

            throw new SystemException("请输入产品类别");
        }

        //构建检索条件
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();

        //用type当作检索条件查询
        productQueryWrapper.eq(DaoConstant.PRODUCT.TYPE, type);

        //查出所有商品名称
        List<Product> productList = iProductService.list(productQueryWrapper);

        //新建一个空ArrayList
        ArrayList<Product> products = new ArrayList<>();

        //创建迭代器
        Iterator<Product> iterator = productList.iterator();

        //使用迭代器
        while (iterator.hasNext()) {

            products.add(iterator.next());
        }

        //返回结果
        return Result.success(products);
    }
}

